<template>
  <div style="width: 100%">
    <div class="modal-url-config-item">
      <el-input
        v-model="url"
        placeholder="请输入路由地址，或者使用下拉框动态生成路由地址"
        clearable
        class="input-item"
      ></el-input>
      <el-select
        v-model="selectValue.id"
        placeholder="选择菜单"
        @change="handleMenuChange"
        clearable
        class="select-item"
      >
        <el-option
          v-for="item in menuList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        ></el-option>
      </el-select>
      <el-select
        v-model="selectValue.field"
        placeholder="选择查询字段"
        @change="handleFieldChange"
        clearable
        class="select-item"
      >
        <el-option
          v-for="item in fieldList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
    </div>
  </div>
</template>
<script setup>
/**
 * 选中菜单和字段，自动生成此菜单地址对应查询URL
 */
import { ref, watch, onMounted } from 'vue';
import ActionAPI from '@/api/admin/dev/action';

const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
});
const emit = defineEmits(['update:modelValue']);
const selectValue = ref({ id: null, route: '', field: '' });
const url = ref('');
const menuList = ref([]);
const fieldList = ref([]);

/**
 * 加载菜单选项
 */
async function fetchMenuOptions() {
  try {
    const { data } = await ActionAPI.getUserMenuOptions();
    menuList.value = data;
    // 菜单加载完成后，尝试初始化URL
    initializeUrl(props.modelValue);
  } catch (err) {
    console.error('Failed to load menu options:', err);
    // 可以在这里向用户显示错误消息
  }
}

// 菜单选中事件
async function handleMenuChange(id) {
  selectValue.value.id = id;
  if (!id) {
    selectValue.value.route = '';
    fieldList.value = [];
    selectValue.value.field = '';
    updateUrl();
    return;
  }
  try {
    const selectedMenu = menuList.value.find((item) => item.id === id);
    selectValue.value.route = selectedMenu ? selectedMenu.route : '';
    const { data } = await ActionAPI.getMenuFields({ menu_id: id });
    fieldList.value = data;
    // 如果当前选中的字段不在新的字段列表中，则清空字段选择
    if (
      selectValue.value.field &&
      !fieldList.value.some((f) => f.value === selectValue.value.field)
    ) {
      selectValue.value.field = '';
    }
  } catch (err) {
    console.error('Error fetching fields:', err);
    // 同样，这里可以展示错误信息给用户
  }
  updateUrl();
}

// 字段选中事件
function handleFieldChange(field) {
  selectValue.value.field = field;
  updateUrl();
}

// 更新url
function updateUrl() {
  url.value = selectValue.value.field
    ? `${selectValue.value.route}?${selectValue.value.field}`
    : selectValue.value.route;
  emit('update:modelValue', url.value);
}

// 初始化URL和下拉菜单选中状态
async function initializeUrl(initialUrl) {
  url.value = initialUrl;
  if (!initialUrl) {
    selectValue.value = { id: null, route: '', field: '' };
    fieldList.value = [];
    return;
  }

  const [routePath, queryString] = initialUrl.split('?');
  const field = queryString || '';

  // 尝试根据routePath找到对应的菜单
  const foundMenu = menuList.value.find((menu) => menu.route === routePath);

  if (foundMenu) {
    selectValue.value.id = foundMenu.id;
    selectValue.value.route = foundMenu.route;
    // 加载字段列表
    try {
      const { data } = await ActionAPI.getMenuFields({
        menu_id: foundMenu.id,
      });
      fieldList.value = data;
      selectValue.value.field = field;
    } catch (err) {
      console.error('Error fetching fields during initialization:', err);
    }
  } else {
    // 如果没有找到匹配的菜单，则清空选择
    selectValue.value = { id: null, route: '', field: '' };
    fieldList.value = [];
  }
}

// 监听modelValue的变化来回显
// watch(
//   () => props.modelValue,
//   (newVal) => {
//     initializeUrl(newVal);
//   },
//   { immediate: true },
// ); // immediate: true 确保在组件挂载时立即执行一次

onMounted(() => {
  fetchMenuOptions();
});
</script>
<style scoped>
.modal-url-config-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.select-item,
.input-item {
  width: 33%;
  margin-right: 10px;
}
</style>
